package com.winit.openapi.apiadapter.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.outbound.OutboundOrderBatchImportService;
import com.winit.oms.spi.outbound.OutboundOrderService;
import com.winit.oms.spi.outbound.command.order.BatchVoidOutboundOrderCommand;
import com.winit.oms.spi.outbound.command.order.OutboundOrderCommand;
import com.winit.oms.spi.outbound.vo.OutboundOrderVo;
import com.winit.oms.spi.vo.v2.response.ErrorResult;
import com.winit.oms.spi.vo.v2.response.VoidResponse;
import com.winit.openapi.constants.EnumConstant.OrderStatus;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiAdapteException;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.APISysConfigUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 作废海外仓出库单适配
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2016年12月29日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
public class VoidOrderAdapteController extends AbstractAdapteController {

    private static final Logger             logger = LoggerFactory.getLogger(VoidOrderAdapteController.class);

    @Resource
    private OutboundOrderBatchImportService outboundOrderBatchImportService;

    @Resource
    private OutboundOrderService            outboundOrderService;

    @Resource
    private APISysConfigUtil                apiSysConfigUtil;

    @RequestMapping(value = "/voidOutboundOrder")
    public String voidOutboundOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        return doAdapte(requestMsg, responseMsg);
    }

    @Override
    protected void validateInputJson(RequestMsg requestMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        if (null == json) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 订单号必填
        ValidateUtil.validNotNull(json, "outboundOrderNum");
        ValidateUtil.validMaxLength(json, "outboundOrderNum", 64, true);

    }

    @Override
    public boolean checkCustomerTansferConfig(RequestMsg requestMsg, ResponseMsg responseMsg) {
        // JSONObject json =
        // JSONObject.parseObject(requestMsg.getData().toString());
        //
        // String orderNo = json.getString("outboundOrderNum");

        return true;
    }

    @Override
    public void doAdapteInOpenAPI(RequestMsg requestMsg, ResponseMsg responseMsg) {
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        String orderNo = json.getString("outboundOrderNum");

        OutboundOrderCommand queryCommand = new OutboundOrderCommand();
        OutboundOrderVo vo = new OutboundOrderVo();
        vo.setOrderNo(orderNo);
        queryCommand.setOrder(vo);
        queryCommand.setCtx(CommandContext.getContext());

        OutboundOrderVo orderVo = outboundOrderService.queryOrderByOrderNo(queryCommand);
        if (orderVo == null) {
            throw new ApiException(ErrorCode.ORDER_NO_NOT_EXSIT, orderNo);
        }
        
        BatchVoidOutboundOrderCommand command = new BatchVoidOutboundOrderCommand();
        List<String> orderNoList = new ArrayList<String>();
        orderNoList.add(orderNo);
        command.setOrderNoList(orderNoList);
        VoidResponse response = outboundOrderBatchImportService.batchVoidOrder(command);
        // 有失败原因的，直接返回
        if (!CollectionUtils.isEmpty(response.getErrorResultList())) {
            ErrorResult errorResult = response.getErrorResultList().get(0);
            throw new ApiAdapteException(errorResult.getErrorCode(), errorResult.getErrorMsg());

        } else {// 无失败原因的，表示作废请求已经提交，具体作废结果未知
            int times = 5;
            try {
                String tryCount = apiSysConfigUtil.getConfigValueByKey("API_VOID_OUTBOUND_ORDER_RETRY_TIMES");
                if (StringUtils.isNotBlank(tryCount)) {
                    times = Integer.valueOf(tryCount);
                }
            } catch (Exception e1) {
                times = 5;
                logger.warn("读取配置项API_VOID_OUTBOUND_ORDER_RETRY_TIMES异常，使用默认配置：" + times + "异常原因：" + e1);

            }

            for (int i = 0; i < times; i++) {
                orderVo = outboundOrderService.queryOrderByOrderNo(queryCommand);
                if (null != orderVo) {
                    String orderStatus = orderVo.getStatus();
                    if (OrderStatus.VO.getStatus().equalsIgnoreCase(orderStatus)) {
                        // 如果查询状态为VO的就返回作废成功
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("outboundOrderNum", orderNo);
                        responseMsg.setData(map);
                        return;
                    } else if (StringUtils.isNotBlank(orderVo.getCancelResultDesc())) {
                        // 如果作废失败，立即返回失败原因
                        logger.warn("作废订单失败,单号：" + orderNo + "原因:" + orderVo.getCancelResultDesc());
                        throw new ApiException(ErrorCode.API_WH_VOID_ORDER_ERROR, orderVo.getCancelResultDesc());
                    }
                    try {
                        Thread.sleep(600);
                    } catch (InterruptedException e) {
                        logger.warn(e.getLocalizedMessage());
                    }
                }

            }
        }
        // 循环查询仍然状态不对的返回作废失败信息
        if (orderVo != null) {
            if (OrderStatus.VOI.getStatus().equalsIgnoreCase(orderVo.getStatus())) {
                logger.warn("订单正在作废中，订单单号：" + orderNo + " 订单状态：" + orderVo.getStatus());
                throw new ApiException(ErrorCode.API_WH_VOID_ORDER_WARN);
            } else if (StringUtils.isBlank(orderVo.getCancelResultDesc())) {// 如果作废请求超时，提示稍后查询
                logger.warn("作废订单返回结果超时，订单单号：" + orderNo + " 订单状态：" + orderVo.getStatus());
                throw new ApiException(ErrorCode.API_WH_VOID_ORDER_WARN);

            }
        }

    }

}
